//
//  CZOAuthViewController.swift
//  WHWeiBo
//
//  Created by Li Changjian on 16/7/10.
//  Copyright © 2016年 Li Changjian. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

/// 请求OAthur授权的地址
let OAuthUrl = "https://api.weibo.com/oauth2/authorize"
/// 申请应用时分配的AppKey
let client_id = "1460982030"
/// 申请应用时分配的AppSecret
let client_secret = "eb589c84d966800bb2959f0b521f6fee"
/// 授权回调地址
let redirect_uri = "http://www.baidu.com"


class CZOAuthViewController: UIViewController {
    
    lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.whiteColor()
        
        setUpNavi()
        
        //加载授权请求界面
        let urlString = OAuthUrl + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        
    }
    // MARK: - 设置navigationItem
    func setUpNavi() {
        title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
    }
    // MARK: - 取消操作
    @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK: - 自动填充
    @objc private func autoFillAction() {
//        print("自动填充")
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'log1069731913@sina.com';document.getElementById('passwd').value = 'my970512'")
    }
    
  
    
    
}

// MARK: - webView代理方法
extension CZOAuthViewController : UIWebViewDelegate {
    //将要加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        let urlString = request.URL?.absoluteString
        
        guard let url = request.URL else {
            return false
        }
//        print(url.absoluteString)
        //判断请求的地址前缀是否为 授权回调地址
        if !url.absoluteString.hasPrefix(redirect_uri) {
            return true
        }
        //代码执行到此,将要请求到的页面为授权回调地址
        //获取请求地址中的code用于access_token接口，获取授权后的accesstoken
        if let query = url.query where query.hasPrefix("code=") {
            let code = query.substringFromIndex("code=".endIndex)
            
            print("code = " + code)
            //ViweModel发送请求获取数据
            CZUserAccountViewModel.sharedUserAccount.requestAccessToken(code) { (isSuccess) -> () in
                if isSuccess {
                    print("登录成功")
                    
                    //发送通知让app切换根视图为欢迎页面
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        
                        SVProgressHUD.dismiss()
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerNotification, object: self)
                    })
                    
                    
                    
                    
                }else {
                    print("登录失败")
                }
            }
        }else {
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        
        return false
    }
    
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
//        webView.scrollView.contentSize = CGSize.zero
        SVProgressHUD.show()
        
    }
    //完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
//        print(error)
        SVProgressHUD.dismiss()
    }
    

}
